package com.ruoyi.controller;


import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.entity.JrFile;
import com.ruoyi.entity.JrFolder;
import com.ruoyi.entity.vo.FolderVO;
import com.ruoyi.mapper.FolderMapper;
import com.ruoyi.service.FolderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 实现文件夹相关操作
 */
@Slf4j
@Api(tags = "FolderController   api")
@RestController
@RequestMapping("/api/folder")
public class FolderController extends BaseController {
    @Autowired
    private FolderService folderService;

    @Autowired
    private FolderMapper folderMapper;

    @PutMapping("/{folderId}/renameFolder")
    public AjaxResult renameFolder(@PathVariable Long folderId, @RequestBody Map<String, String> request) {
        String newName = request.get("newName");
        if (StringUtils.isBlank(newName)) {
            return AjaxResult.error("新文件夹名不能为空");
        }

        try {
            int result = folderService.renameFolder(folderId, newName);
            return result > 0 ? AjaxResult.success() : AjaxResult.error("重命名失败");
        } catch (ServiceException e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @PutMapping("/{folderId}/expirationDate")
    public AjaxResult expirationDate(@PathVariable Long folderId, @RequestBody Map<String, Date> request) {
        Date expirationDate = request.get("expirationDate");
        System.out.println("111###"+expirationDate);
        try {
            int result = folderService.setExpirationDate(folderId, expirationDate);
            return result > 0 ? AjaxResult.success() : AjaxResult.error("有效日期设置失败");
        } catch (ServiceException e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @DeleteMapping("/{folderId}")
    public AjaxResult deleteFolder(@PathVariable Long folderId) {
        System.out.println("FolderController文件夹删除：" +folderId);
        return toAjax(folderService.deleteFolder(folderId));
    }

    @PostMapping
    @ApiOperation("创建文件夹")
    @RequestMapping("/createFolder")
    public AjaxResult createFolder(@RequestBody JrFolder folder) {
        JrFolder folder1 = folderService.createFolder(folder);
        System.out.println("返回-----------------------        "+    folder1);
        return AjaxResult.success(folder1);
    }

    /**
     * 获取知识库树形菜单信息
     * @return
     */
    @GetMapping("/trees")
    @ApiOperation("获取树形菜单")
    public AjaxResult getFolderTrees() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        List<FolderVO> tree = folderService.getFolderTrees(user);
        System.out.println("-------------------获取知识库树形菜单信息------------------------:    "+ tree);
        return AjaxResult.success(tree);
    }

    /**
     * 获取权限树形菜单信息
     * @return
     */
    @GetMapping("/tree")
    @ApiOperation("获取树形菜单")
    public AjaxResult getFolderTree() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        List<FolderVO> tree = folderService.getFolderTree(user);
        System.out.println("-------------------获取权限树形菜单信息------------------------:    "+ tree);
        return AjaxResult.success(tree);
    }

    @ApiOperation("idd-----")
    @GetMapping("/{folderId}/contents")
    public AjaxResult getFolderContents(
            @PathVariable Long folderId) {

        log.info("查询文件夹内容：{}，用户：{}", folderId, SecurityUtils.getUsername());

        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();

        //获取当前文件
        JrFolder currentFolder = folderMapper.selectById(folderId);
        if (currentFolder == null) {
            return AjaxResult.error("文件夹不存在");
        }
        log.info("当前文件夹：{}", currentFolder);

        // 2. 权限校验（包含密级校验）
        if (currentFolder.getSecurity() > user.getSecurity()) {
            throw new AccessDeniedException("无权访问该文件夹");
        }
        System.out.println("文件夹id=             :     "+currentFolder.getId());

        // 查询直接子文件夹
        List<JrFolder> childFolders = folderMapper.selectChildFolders(
                currentFolder.getId(),
                user.getUserId(),
                user.getSecurity()
        );

        System.out.println( "文件夹 ：  "+    childFolders);
        // 查询直接关联的文件
        List<JrFile> files = folderMapper.selectFilesByAncestorPath(
                currentFolder.getId(),
                user.getSecurity(),
                user.getUserId()
        );

        Map<String, Object> result = new HashMap<>();
        result.put("currentFolder", currentFolder);
        result.put("childFolders", childFolders);
        result.put("files", files);

        log.info("查询到子文件夹：{} 个", childFolders.size());
        log.info("查询到文件：{} 个", files.size());

        return AjaxResult.success(result);
    }
}
